package com.uchengwang.ui.cm_ui.me.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.uchengwang.R;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.config.ClubConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.listener.OnHttpResultListener;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.functions.http.manager.HttpManager;
import com.uchengwang.ui.base_ui.ui.BaseWithTitleActivity;
import com.uchengwang.ui.cm_ui.login.bean.UserBean;
import com.uchengwang.ui.cm_ui.me.adapter.TransferClubAdapter;
import com.uchengwang.ui.cm_ui.rychat.bean.InviteUserBean;
import com.uchengwang.ui.cm_ui.rychat.bean.RyUserBean;
import com.uchengwang.ui.cm_ui.rychat.manager.RyGroupManager;
import com.uchengwang.ui.cm_ui.ucity.cityBean.UserBeanList;
import com.uchengwang.ui.utils.JsonUtils;
import com.uchengwang.ui.utils.LoadingUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by U城网 on 2017/7/5.
 * 社团账户成员管理 前期界面
 */

public class ClubMemberActivity extends BaseWithTitleActivity{
    private RecyclerView recycleView;
    private PtrClassicFrameLayout mSwipeRefreshLayout;
    private RecyclerAdapterWithHF mAdapter;
    private TransferClubAdapter transferAdapter;

    private int page = 1, totlaPagers;
    private long orgId;
    private int type;//0查看普通成员  1转让管理权 2邀请社团成员加入默认创建的社团群
    private String code;//社团转让需要验证码
    private long groupId;//群ID
    private String groupName;
    private List<RyUserBean> memmbers;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_ustudy_2);
        orgId = getIntent().getLongExtra(BaseConfig.ORG_ID, -1);
        groupId = getIntent().getLongExtra(BaseConfig.GROUP_ID, 0);
        groupName = getIntent().getStringExtra(BaseConfig.GROUP_NAME_UCW);
        type = getIntent().getIntExtra(BaseConfig.TYPE, 0);

        switch (type){
            case 0:
                setTitle("成员");
                setRightText("添加", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        List<UserBean> list = transferAdapter.getData();
                        List<String> longs = null;
                        if (list != null && list.size() >0){
                            int size = list.size();
                            longs = new ArrayList<String>();
                            for (int i =0; i<size; i++){
                                longs.add(String.valueOf(list.get(i).getId()));
                            }

                        }
                        Intent intent = new Intent(ClubMemberActivity.this, AddClubMemberActivity.class);
                        if (longs != null){
                            intent.putStringArrayListExtra(BaseConfig.LIST, (ArrayList<String>) longs);
                        }
                        startActivity(intent);
                    }
                });
                break;
            case 1:
                code = getIntent().getStringExtra(BaseConfig.CODE);
                setTitle("转让管理权");
                break;
            case 2://邀请社团成员加群
                setTitle("邀请加群");

                setRightText("邀请", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        addMember();
                    }
                });
                break;
        }


        initView();
    }

    private void initView(){
        recycleView = (RecyclerView) findViewById(R.id.u_study_recycleView);
        mSwipeRefreshLayout = (PtrClassicFrameLayout) findViewById(R.id.mRefreshLayout);

        initData();
    }

    private void initData(){
        recycleView.setLayoutManager(new LinearLayoutManager(this));
        transferAdapter = new TransferClubAdapter(this, type);
        mAdapter = new RecyclerAdapterWithHF(transferAdapter);
        recycleView.setAdapter(mAdapter);

        switch (type){
            case 1:
                transferAdapter.setCode(code);
                break;
        }

        mSwipeRefreshLayout.setAutoLoadMoreEnable(true);
        mSwipeRefreshLayout.setLoadMoreEnable(true);

        mSwipeRefreshLayout.postDelayed(new Runnable() {

            @Override
            public void run() {
                mSwipeRefreshLayout.autoRefresh(true);
            }
        }, 150);

        mSwipeRefreshLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                page= 1;
                mSwipeRefreshLayout.loadMoreComplete(true);
                getClubMembers(true);
            }
        });

        mSwipeRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                page++;
                if (page <= totlaPagers){
                    //当前请求页大于总页数，不再请求
                    getClubMembers(false);
                } else {
                    mSwipeRefreshLayout.loadMoreComplete(false);
                }
            }
        });
    }

    /**
     * 获取社团成员
     * */
    private void getClubMembers(final boolean isRefresh){
        MapRequest map = new MapRequest();
        map.put(BaseConfig.PAGE, page);
        map.put(BaseConfig.PERPAGE, 20);
//        map.put(BaseConfig.IS_ACCEPT, true);
        map.put(BaseConfig.ORG_ID, orgId);

        HttpManager.newInstance(this).query(ClubConfig.ClubMemeber.method, ClubConfig.ClubMemeber.URL, map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                Log.d("jjf", "status="+status+"=msg="+msg);
                UCommonUtil.getUtil().showToast(ClubMemberActivity.this, "获取失败");
                if (isRefresh){
                    mSwipeRefreshLayout.refreshComplete();
                }else {
                    mSwipeRefreshLayout.loadMoreComplete(true);
                }

            }

            @Override
            public void onResp(int status, String msg, String data) {
                Log.d("jjf", "status="+status+"=msg="+msg);
                if (isRefresh){
                    mSwipeRefreshLayout.refreshComplete();
                }else {
                    mSwipeRefreshLayout.loadMoreComplete(true);
                }

                if (status != 0){
                    UCommonUtil.getUtil().showToast(ClubMemberActivity.this, msg);
                    return;
                }

                if (!TextUtils.isEmpty(data)){
                    UserBeanList beanList = JsonUtils.getManager().stringToBean(data, UserBeanList.class);
                    if (beanList != null){
                        totlaPagers = beanList.getTotalPage();
                        List<UserBean> list = beanList.getData();

                        if (isRefresh){
                            transferAdapter.setData(list);
                        }else {
                            transferAdapter.getData().addAll(list);
                            transferAdapter.notifyDataSetChanged();
                        }


                        //获取到群成员
                        if (memmbers == null || BaseConfig.isRelease){
                            getGroupMembers();
                        }else {
                            transferAdapter.setMembers(memmbers);
                        }
                    }
                }
            }
        });
    }

    /**
     * 调取环信的接口,获取群组信息
     * */
    private void getGroupMembers(){
        if (groupId <1){
            return;
        }
        RyGroupManager.getManager().getGroupMembers(this, groupId, 1, 999, new OnHttpResultListener<RyUserBean>() {
            @Override
            public void onResult(int status, String msg, int total, List<RyUserBean> list) {
                if (list == null || list.size() <1){
                    return;
                }
                memmbers = list;
                if (memmbers != null && memmbers.size() >0){
                    transferAdapter.setMembers(memmbers);
                }
            }
        });

    }

    /**
     * 邀请加群
     * */
    private List<UserBean> checkUsers;//选中的用户
    private void addMember(){
        LoadingUtils.getUtils().loading(this);

        if (transferAdapter!= null){
            List<UserBean> list = transferAdapter.getData();
            checkUsers = new ArrayList<>();
            int size = list.size();
            for (int i=0; i<size; i++){
                //将选中的对象筛选出来
                UserBean b = list.get(i);
                if (b.isCheck()){
                    checkUsers.add(b);
                }
            }
        }

        if (checkUsers == null || checkUsers.size() < 1){
            LoadingUtils.getUtils().hide();
            UCommonUtil.getUtil().showToast(this, "请选择");
            return;
        }

        addMember(checkUsers);


    }

    /**
     * 添加群成员
     * */
    private void addMember(List<UserBean> list){
        List<InviteUserBean> userBeanList = new ArrayList<>();
        for (UserBean userBean : list){
            //选中邀请的好友
            InviteUserBean inviteUserBean = new InviteUserBean();
            inviteUserBean.setGroupId(groupId);
            inviteUserBean.setGroupName(groupName);
            inviteUserBean.setInviteMsg("欢迎您");
            inviteUserBean.setToUid(userBean.getId());
            inviteUserBean.setToNickName(userBean.getNickName());
            inviteUserBean.setToUserAvatar(userBean.getUserAvatar());

            userBeanList.add(inviteUserBean);
        }

        RyGroupManager.getManager().inviteMember(this, userBeanList, new OnResultListener() {
            @Override
            public void onResult(int stutas, String msg, int total, String data) {
                LoadingUtils.getUtils().hide();
                if (stutas ==0){
                    UCommonUtil.getUtil().showToast(ClubMemberActivity.this, "邀请成功");
                }else {
                    UCommonUtil.getUtil().showToast(ClubMemberActivity.this, "邀请失败, 请重试");
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        List<UserBean> l = transferAdapter.getData();
        l.clear();
        if (memmbers != null){
            memmbers.clear();
            memmbers = null;
        }
        l = null;
    }
}
